#include "Nesting_graphics.h"

namespace Nesting
{

	static GLfloat pgn_fill_color[] = {0.7f, 0.7f, 0.7f};
	static GLfloat pgn_hightlight_color[] = {0.6f, 0.0f, 0.0f};
	const static GLfloat c1 = 0.35f;
	const static GLfloat c2 = 0.5f;
	const static GLfloat c3 = 1.0f;
	static GLfloat color_table[24][3] = 
	{
		{c3, c2, c2},
		{c2, c3, c2},
		{c2, c2, c3},
		{c2, c3, c3},
		{c3, c2, c3},
		{c3, c3, c2},

		{c1, c2, c2},
		{c2, c1, c2},
		{c2, c2, c1},
		{c2, c1, c1},
		{c1, c2, c1},
		{c1, c1, c2},

		{c1, c3, c3},
		{c3, c1, c3},
		{c3, c3, c1},
		{c3, c1, c1},
		{c1, c3, c1},
		{c1, c1, c3},

		{c1, c2, c3}, 
		{c1, c3, c2}, 
		{c2, c1, c3}, 
		{c2, c3, c1}, 
		{c3, c1, c2}, 
		{c3, c2, c1}
	} ;

	static int random_color_index_ = 0 ;
	static void gl_random_color() {
		glColor3f(
			color_table[random_color_index_][0], 
			color_table[random_color_index_][1], 
			color_table[random_color_index_][2]
		) ;
		random_color_index_ = (random_color_index_ + 1) % 12 ;
	}
	static void gl_random_color(int index) {
		random_color_index_ = index % 12 ;
		gl_random_color() ;
	}
	static void gl_randomize_colors() {
		random_color_index_ = 0 ;
	}
	Nesting_graphics::Nesting_graphics(Nester* _nester) : nester(_nester)
	{
		show_container = GL_TRUE;
		show_polytopes = GL_TRUE;
		show_bdbox = GL_FALSE;
		highlight_no = -1;
		pre_highlight_no = highlight_no;
	}
	Nesting_graphics::~Nesting_graphics()
	{

	}
	void Nesting_graphics::draw()
	{
		glUseProgramObjectARB(0);
		
		gl_randomize_colors();
		if (show_container)
			nester->cbox->gl_draw();
		if (show_polytopes)
		{
			//std::for_each(nester->polytope_set.begin(), nester->polytope_set.end(), std::bind2nd(std::mem_fun(&Nesting_polytope::gl_draw), pgn_fill_color));
			for (unsigned int i = 0; i < nester->polytope_set.size(); i++)
			{
				if (i == highlight_no && highlight_no != pre_highlight_no)
				{
					//nester->polytope_set.at(i)->gl_draw(pgn_fill_color);
					nester->polytope_set.at(i)->redraw(pgn_hightlight_color);
					if (pre_highlight_no >= 0 && pre_highlight_no < nester->polytope_set.size())
						nester->polytope_set.at(pre_highlight_no)->redraw(pgn_fill_color);
					pre_highlight_no = highlight_no;
				}
				else
					nester->polytope_set.at(i)->gl_draw(pgn_fill_color);
				/*if (highlight_no >= 0 && highlight_no < nester->polytope_set.size())
					nester->polytope_set.at(highlight_no)->gl_draw(pgn_hightlight_color);*/
			}
		}
		if (show_bdbox)
			std::for_each(nester->polytope_set.begin(), nester->polytope_set.end(), std::mem_fun(&Nesting_polytope::gl_draw_bbox));

		// debug
		//for (unsigned int i = 0; i < nester->op.size(); i++)
		//{
		//	nester->op.at(i)->gl_draw_keypoints();
		//}
	}
}
